use std::sync::{Arc, Mutex};
use crossbeam_channel::{bounded, Sender};

#[derive(Debug, Clone)]
pub struct Broadcaster<T> {
    pub subscribers: Arc<Mutex<Vec<Sender<T>>>>,
}

impl<T: Clone + Send + 'static> Broadcaster<T> {
    pub fn new() -> Self {
        Self {
            subscribers: Arc::new(Mutex::new(Vec::new())),
        }
    }
    
    pub fn subscribe(&self) -> crossbeam_channel::Receiver<T> {
        let (tx, rx) = bounded(10);
        self.subscribers.lock().unwrap().push(tx);
        rx
    }
    
    pub fn broadcast(&self, msg: T) {
        let subs = self.subscribers.lock().unwrap();
        for sub in subs.iter() {
            let _ = sub.send(msg.clone()); // 忽略发送错误
        }
    }
}